package studio7Omega.servlet;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import studio7Omega.excepcion.DAOExcepcion;
import studio7Omega.modelo.Usuario;
import studio7Omega.negocio.SistemaNegocio;

/**
 * Servlet implementation class loginServlet
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		HttpSession session = request.getSession();
		String usuario = request.getParameter("usuario");
		String clave= request.getParameter("clave");
		String invitado = request.getParameter("invitado");
		
		if ( usuario == null ) usuario = "";
		if ( clave == null ) clave = "";
		if ( invitado != null )
		{
			usuario = "invitado"; 
			clave = "";
		}
		
		SistemaNegocio nego = new SistemaNegocio();
		try {
			Usuario user = nego.login( usuario, clave );
			int idUsuario = user.getIdUsuario();
			
			session.setAttribute( "USUARIO", user );
			if ( idUsuario >= 0 )
			{
				response.sendRedirect( "menu.jsp" );				
			}
			else
			{
				response.sendRedirect( "login.jsp" );
			}
			return;
		} catch (DAOExcepcion e) {
			System.out.println("Error");
			RequestDispatcher rd = request.getRequestDispatcher( "error.jsp" );
			rd.forward(request, response);
		}
	}

}
